import platform = require('../../../../platform/common/baseCommon');
import appClient = require('../../../../platform/client/appClient');
import platformControls = require('../../../../platform/client/controls');
import report = require('../../../../platform/client/report');

let moduleName = "platform.test";

@platform.addon("关系视图", "关系视图", moduleName)
@appClient.template("project/test/views/test/graph.html")
export class graphView extends appClient.baseView {

    /**
     * 数据服务
     */
    dataService?: platform.IDataService;

    /**
     * 对象:EChart
     */
    private myChart?: echarts.echarts = undefined;
    /**
     * 提示框(dialog)
     */
    private myDialog?: platformControls.dialog = undefined;

    private data?: any = undefined;

    /**
     * 配置:EChart Option
     */
    graphOption?: any = {
        title: {
            text: ''
        },
        tooltip: {
            triggerOn: 'click',
            formatter: function (params: any, ticket: any, callback: any) {
                if (params.dataType === 'node') {
                    var url = `name=${params.name}&x=${params.data.longitude}&y=${params.data.latitude}`;
                    var urls = encodeURI(url);
                    var html = `<div style="display:inline-block;with:150px;"><p>${params.name}</p>
                                    <p>所属地区：广东省佛山市</p>
                                    <p>经营状态：在营（开业）</p>
                                    <p>地址：${params.data.scjydz}</p>
                                    <input type="button" class="btn btn-default btn-xs" value="查看详情" onclick=";"></input>
                                </div> 
                                <div id="ifr" style="display:inline-block"><iframe src="project/test/views/test/baidumap.html?${urls}"></iframe></div>`;
                    return html;
                }
            }
        },
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        label: {
            normal: {
                show: true,
                position: 'bottom',
                textStyle: {
                    fontSize: 8
                }
            }
        },
        legend: {
            x: "right",
            y: "bottom",
            show: true,
            right: 20,
            data: []
        },
        series: [
            {
                type: 'graph',
                layout: 'none',
                symbolSize: 40,
                focusNodeAdjacency: true,
                roam: true,
                label: {
                    normal: {
                        show: true,
                        textStyle: {
                            fontSize: 12
                        }
                    }
                },
                force: {
                    repulsion: 500
                },
                edgeSymbol: ['none', 'arrow'],
                edgeSymbolSize: [4, 10],
                // symbol: 'image://images/企业图标1.png',
                lineStyle: {
                    normal: {
                        opacity: 0.9,
                        width: 1,
                        curveness: 0
                    }
                },
                itemStyle: {
                    emphasis: {
                        borderColor: 'rgb(238,201,0)',
                        borderWidth: 5,
                        opacity: 0
                    }
                },
                data: [],
                links: [],
                animationDelay: function (idx: number) {
                    return idx * 100;
                }
            }
        ],
        animationDelayUpdate: function (idx: number) {
            return idx * 100;
        }
    };

    /**
     * 元素:EChart div
     */
    $myChart?: HTMLDivElement = undefined;

    /**
     * 事件:绑定后
     * @remark 只绑定一次
     */
    onAfterBind?() {
        let that = this;
        that.myDialog = new platformControls.dialog();
        that.myDialog.appendTo(this.element);
        window.onresize = function () {
            //重置容器高宽
            that.resetsize();
            that.myChart.resize();
        };
        that.resetsize();
        that.myChart = echarts.init(that.$myChart[0]);
        let toolbox = {
            show: true,
            orient: 'vertical',
            x: 'left',
            y: 'center',
            left: 20,
            feature: {
                mySingle: {
                    show: true,
                    title: "单点定位",
                    icon: 'image://project/test/views/images/select/single.png',
                    onclick: () => {
                        that.singleBind();
                    }
                }
            }
        };
        that.graphOption.toolbox = toolbox;
        that.graphOption.legend.data = ["合资", "私营", "集体所有制", "股份制", "有限责任"];
        that.graphOption.series[0].categories = [{ name: "合资" }, { name: "私营" }, { name: "集体所有制" }, { name: "股份制" }, { name: "有限责任" }];
        that.myChart.setOption(that.graphOption);
        that.data = [];
    }

    /**
     * 重置大小
     */
    resetsize?() {
        let $div = this.$myChart[0];
        //为兼容ie8需要做判断
        if (window.innerWidth) {
            $div.style.width = window.innerWidth + 'px';
        } else {
            $div.style.width = document.documentElement.clientWidth + 'px';
        }

        if (window.innerHeight) {
            $div.style.height = (window.innerHeight - 115) + 'px';
        } else {
            $div.style.height = (document.documentElement.clientHeight - 115) + 'px';
        }
    }

    /**
     * 事件:显示后
     */
    onShowed?() {
        this.graphOption.series[0].data = [];
        this.graphOption.series[0].links = [];
        this.asyncLoad();
    }


    /**
     * 异步
     */
    asyncLoad?() {
        let that = this;
        that.myChart.showLoading();
        try {
            that.dataService
                .query("cmd_dj_nsrxx", {})
                .then((dataTable: platform.dataTable) => {
                    try {
                        if (dataTable && dataTable.rows && dataTable.rows.length > 0) {
                            dataTable.rows.map(function (item: any, index: number) {
                                item.rowValues.name = item.rowValues.nsrmc;
                                item.rowValues.draggable = true;
                                item.rowValues.x = random(1, 1000);
                                item.rowValues.y = random(10, 800);
                                let link: any = {};
                                link.source = index;
                                link.target = item.rowValues.target;
                                that.graphOption.series[0].data.push(item.rowValues);
                                that.data.push(item.rowValues);
                                that.graphOption.series[0].links.push(link);
                                return item.rowValues;
                            });
                            that.myChart.setOption(that.graphOption, false, true);
                            that.startIndex = that.startIndex + that.maxCount;
                        }
                    } catch (e) {
                        console.error(e);
                    } finally {
                        that.myChart.hideLoading();
                    }
                });
        } catch (error) {
            console.error(error);
        }
    }

    smartInputBind?() {
        var list = this.data.map(function (item: any) {
            return item.name;
        });
        $('.typeahead').typeahead({
            source: function (query: any, process: any) {
                process(list);
            }
        });
    }

    singleBind?() {
        let that = this;
        that.myDialog.onControlBind = () => {
            that.smartInputBind();
        };
        that.myDialog.onDialogSubmitClick = () => {
            let name = $('#searchSingle').text();
            if (name) {
                that.myChart.dispatchAction({
                    type: 'highlight',
                    name: name
                });
            }
        };
        that.myDialog.show("单点定位",
            `<div class="input-group">
                <span class="input-group-addon">公司名称</span>
                <input id="searchSingle" type="text" class="form-control typeahead" data-provide="typeahead">
            </div>`);
    }
}

/**
 * 随机整数
 * @param minNum 最小值
 * @param maxNum 最大值
 */
export function random(minNum?: number, maxNum?: number) {
    switch (arguments.length) {
        case 1:
            return Math.random() * minNum + 1;
        case 2:
            return Math.random() * (maxNum - minNum + 1) + minNum;
        default:
            return 0;
    }
}